package com.crazyhat.crazyhat.service.impl;

import static com.crazyhat.crazyhat.attribute.ClubPositionEnum.LEADER;
import static com.crazyhat.crazyhat.attribute.ClubPositionEnum.MEMBER;
import static com.crazyhat.crazyhat.attribute.ClubPositionEnum.SECOND_LEADER;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crazyhat.crazyhat.attribute.ClubPositionEnum;
import com.crazyhat.crazyhat.attribute.ClubStatusEnum;
import com.crazyhat.crazyhat.attribute.PostPublicScopeEnum;
import com.crazyhat.crazyhat.attribute.TokenPayloadEnum;
import com.crazyhat.crazyhat.attribute.UserTypeEnum;
import com.crazyhat.crazyhat.config.ClubPopularityConfig;
import com.crazyhat.crazyhat.config.RecentPeriodConfig;
import com.crazyhat.crazyhat.dto.ClubApprovalDTO;
import com.crazyhat.crazyhat.dto.ClubApprovalDetailDTO;
import com.crazyhat.crazyhat.dto.ClubDetailsDTO;
import com.crazyhat.crazyhat.dto.ClubManagementDTO;
import com.crazyhat.crazyhat.dto.ClubUpdateRequestDTO;
import com.crazyhat.crazyhat.dto.CreateClubDTO;
import com.crazyhat.crazyhat.entity.Activity;
import com.crazyhat.crazyhat.entity.AdminMessage;
import com.crazyhat.crazyhat.entity.Application;
import com.crazyhat.crazyhat.entity.Club;
import com.crazyhat.crazyhat.entity.Comment;
import com.crazyhat.crazyhat.entity.Footprint;
import com.crazyhat.crazyhat.entity.Participation;
import com.crazyhat.crazyhat.entity.Post;
import com.crazyhat.crazyhat.entity.User;
import com.crazyhat.crazyhat.mapper.ActivityMapper;
import com.crazyhat.crazyhat.mapper.AdminMessageMapper;
import com.crazyhat.crazyhat.mapper.ApplicationMapper;
import com.crazyhat.crazyhat.mapper.ClubMapper;
import com.crazyhat.crazyhat.mapper.CommentMapper;
import com.crazyhat.crazyhat.mapper.FootprintMapper;
import com.crazyhat.crazyhat.mapper.ParticipationMapper;
import com.crazyhat.crazyhat.mapper.PostMapper;
import com.crazyhat.crazyhat.mapper.UserMapper;
import com.crazyhat.crazyhat.pojo.ClubCategory;
import com.crazyhat.crazyhat.service.IClubService;
import com.crazyhat.crazyhat.service.IFootprintService;
import com.crazyhat.crazyhat.service.IMessageService;
import com.crazyhat.crazyhat.service.IParticipationService;
import com.crazyhat.crazyhat.utils.ObsUtil;
import com.crazyhat.crazyhat.utils.ThreadLocalUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * <p>
 * 社团 服务实现类
 * </p>
 *
 * @author crazyhat
 * @since 2024-07-05
 */
@Service

public class ClubServiceImpl extends ServiceImpl<ClubMapper, Club> implements IClubService {
    @Value("${my-config.aliyun-OSS-config.imageDirectory}")
    private String imageDirectory;

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private ApplicationMapper applicationMapper;

    @Autowired
    private FootprintMapper footPrintMapper;

    @Autowired
    private ClubMapper clubMapper;

    @Autowired
    private ParticipationMapper participationMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private AdminMessageMapper adminMessageMapper;

    @Autowired
    private ClubCategory clubCategory;

    @Autowired
    private RecentPeriodConfig recentPeriodConfig; // 注入配置类

    @Autowired
    private IMessageService messageService;

    @Autowired
    private IFootprintService footprintService;


    /**
     * 用于查询用户是否有权查看动态
     */
    @Autowired
    private IParticipationService participationService;

    @Autowired
    private ClubPopularityConfig clubPopularityConfig; // 注入配置类

    // 模糊搜索社团
    @Override
    public List<Club> searchClubs(String keyword, List<String> categories) {
        QueryWrapper<Club> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .notIn("club_status",
                        ClubStatusEnum.Deleted.getValue(),
                        ClubStatusEnum.InReview.getValue(),
                        ClubStatusEnum.Rejected.getValue())
                .and(wrapper -> wrapper
                        .like("club_name", keyword)
                        .or()
                        .like("leader_name", keyword)
                        .or()
                        .like("category", keyword));

        if (categories != null && !categories.isEmpty()) {
            queryWrapper.in("category", categories);
        }

        return clubMapper.selectList(queryWrapper);
    }

    //获取社团分类
    @Override
    public List<String> getClubCategories() {
        return clubCategory.getClubCategoryList();
    }

    @Override
    public List<Club> getTopClubsByPopularity(int limit) {

        /*
         * 更换为相应的枚举类
         */
        QueryWrapper<Club> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .ne("club_status", ClubStatusEnum.Deleted.getValue())
                .ne("club_status", ClubStatusEnum.InReview.getValue())
                .ne("club_status", ClubStatusEnum.Rejected.getValue())
                .orderByDesc("popularity")
                .last("LIMIT " + limit);
        return clubMapper.selectList(queryWrapper);
    }


    /**
     * 判断该用户是否任该社团的某职位，不可判断非社团成员
     */
    public boolean isSuchClubPosition(ClubPositionEnum clubPositionEnum,Integer clubId){

        if (clubPositionEnum==null || clubId==null) {
            return false;
        }

        Map<String, Object> map = ThreadLocalUtil.get();
        Integer studentId = (Integer) map.get(TokenPayloadEnum.StudentId.getValue());

        QueryWrapper<Participation> queryWrapper=new QueryWrapper<>();
        queryWrapper
            .eq("student_id",studentId)
            .eq("club_id",clubId)
            .eq("club_position", clubPositionEnum.getValue());


        if (participationMapper.selectOne(queryWrapper)!=null) {
            return true;
        }

        return false;
    }


    @Override
    public List<Club> getLatestClubs(int limit) {

        /*
         * 更换为相应的枚举类
         */

        QueryWrapper<Club> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .ne("club_status", ClubStatusEnum.Deleted.getValue())
                .ne("club_status", ClubStatusEnum.InReview.getValue())
                .ne("club_status", ClubStatusEnum.Rejected.getValue())
                .orderByDesc("publish_time")
                .last("LIMIT " + limit);
        return clubMapper.selectList(queryWrapper);
    }

    // 社团管理 获取社团管理所需信息
    @Override
    public List<ClubManagementDTO> getClubManagementInfo() {
        QueryWrapper<Club> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("club_id","club_name", "leader_name", "current_members", "publish_time", "club_status"); // 添加club_status

        return clubMapper.selectList(queryWrapper).stream().map(club -> {
            ClubManagementDTO dto = new ClubManagementDTO();
            dto.setClubId(club.getClubId());
            dto.setClubName(club.getClubName());
            dto.setLeaderName(club.getLeaderName());
            dto.setCurrentMembers(club.getCurrentMembers());
            dto.setCreateTime(club.getPublishTime());
            dto.setClubStatus(club.getClubStatus()); // 设置club_status
            return dto;
        }).collect(Collectors.toList());
    }

    // 社团管理 删除社团
    @Override
    public boolean deleteClubs(List<Integer> clubIds) {
        return this.removeByIds(clubIds);
    }

    // 社团管理 查看社团详情
    @Override
    public ClubDetailsDTO getClubDetails(Integer clubId) {
        Club club = clubMapper.selectById(clubId);

        List<Participation> participations = participationMapper.selectList(
                new QueryWrapper<Participation>().eq("club_id", clubId));

        List<ClubDetailsDTO.MemberInfo> members = participations.stream()
                .map(p -> {
                    User user = userMapper.selectById(p.getStudentId());
                    ClubDetailsDTO.MemberInfo memberInfo = new ClubDetailsDTO.MemberInfo();
                    memberInfo.setStudentId(user.getStudentId());
                    memberInfo.setName(user.getName());

                    if (club.getLeaderId().equals(user.getStudentId())) {
                        memberInfo.setPosition(LEADER.getDescription());
                    } else if (club.getSecondManager() != null && club.getSecondManager().contains(String.valueOf(user.getStudentId()))) {
                        memberInfo.setPosition(ClubPositionEnum.SECOND_LEADER.getDescription());
                    } else {
                        memberInfo.setPosition(ClubPositionEnum.MEMBER.getDescription());
                    }

                    return memberInfo;
                })
                .collect(Collectors.toList());

        ClubDetailsDTO clubDetailsDTO = new ClubDetailsDTO();
        clubDetailsDTO.setClubName(club.getClubName());
        clubDetailsDTO.setLeaderName(club.getLeaderName());
        clubDetailsDTO.setMembers(members);

        return clubDetailsDTO;
    }


    //社团管理 查新用户
    @Override
    public List<ClubDetailsDTO.MemberInfo> searchMember(Integer clubId, String keyword) {
        List<Participation> participations = participationMapper.selectList(
                new QueryWrapper<Participation>().eq("club_id", clubId));

        return participations.stream()
                .map(p -> userMapper.selectById(p.getStudentId()))
                .filter(user -> user.getName().contains(keyword) || String.valueOf(user.getStudentId()).contains(keyword))
                .map(user -> {
                    ClubDetailsDTO.MemberInfo memberInfo = new ClubDetailsDTO.MemberInfo();
                    memberInfo.setStudentId(user.getStudentId());
                    memberInfo.setName(user.getName());

                    Club club = clubMapper.selectById(clubId);
                    if (club.getLeaderId().equals(user.getStudentId())) {
                        memberInfo.setPosition(LEADER.getDescription());
                    } else if (club.getSecondManager() != null && club.getSecondManager().contains(String.valueOf(user.getStudentId()))) {
                        memberInfo.setPosition(ClubPositionEnum.SECOND_LEADER.getDescription());
                    } else {
                        memberInfo.setPosition(ClubPositionEnum.MEMBER.getDescription());
                    }

                    return memberInfo;
                })
                .collect(Collectors.toList());
    }

    //社团管理 用户管理
    @Override
    @Transactional
    public boolean updateMemberPosition(Integer clubId, Integer studentId, String position) throws JsonProcessingException {

        Club club = clubMapper.selectById(clubId);
        if (club == null) {
            return false;
        }

        try {
            // 获取新一把手的信息
            User newLeader = null;
            if (ClubPositionEnum.LEADER.getDescription().equals(position)) {
                newLeader = userMapper.selectById(studentId);
                if (newLeader == null) {
                    return false;
                }
            }
            // 如果新职位是 LEADER，则需要将原先的 LEADER 设置为普通成员
            if (ClubPositionEnum.LEADER.getDescription().equals(position)) {
                Integer oldLeaderId = club.getLeaderId();
                if (oldLeaderId != null && !oldLeaderId.equals(studentId)) {
                    // 更新原先的 LEADER 为普通成员
                    QueryWrapper<Participation> oldLeaderQueryWrapper = new QueryWrapper<>();
                    oldLeaderQueryWrapper.eq("club_id", clubId).eq("student_id", oldLeaderId);
                    Participation oldLeaderParticipation = participationMapper.selectOne(oldLeaderQueryWrapper);
                    if (oldLeaderParticipation != null) {
                        oldLeaderParticipation.setClubPosition(ClubPositionEnum.MEMBER);
                        participationMapper.updateById(oldLeaderParticipation);
                    }
                }
                // 设置新的 LEADER
                club.setLeaderId(studentId);
                club.setLeaderName(newLeader.getName());
                // 从二把手列表中移除新的一把手
                if (club.getSecondManager() != null) {
                    List<Integer> secondManagers = objectMapper.readValue(club.getSecondManager(), new TypeReference<List<Integer>>() {});
                    secondManagers.remove(studentId);
                    club.setSecondManager(objectMapper.writeValueAsString(secondManagers));
                }
            } else {
                // Update second managers
                List<Integer> secondManagers;
                if (club.getSecondManager() == null) {
                    secondManagers = new ArrayList<>();
                } else {
                    secondManagers = objectMapper.readValue(club.getSecondManager(), new TypeReference<List<Integer>>() {});
                }

                if (ClubPositionEnum.SECOND_LEADER.getDescription().equals(position)) {
                    if (!secondManagers.contains(studentId)) {
                        secondManagers.add(studentId);
                    }
                } else {
                    secondManagers.remove(studentId);
                }
                club.setSecondManager(objectMapper.writeValueAsString(secondManagers));
            }
            clubMapper.updateById(club);
            // 更新 participation 表中的数据
            QueryWrapper<Participation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("club_id", clubId).eq("student_id", studentId);
            Participation participation = participationMapper.selectOne(queryWrapper);
            if (participation != null) {
                // Participation record exists, update the position
                if (ClubPositionEnum.LEADER.getDescription().equals(position)) {
                    participation.setClubPosition(ClubPositionEnum.LEADER);
                } else if (ClubPositionEnum.SECOND_LEADER.getDescription().equals(position)) {
                    participation.setClubPosition(ClubPositionEnum.SECOND_LEADER);
                } else {
                    participation.setClubPosition(ClubPositionEnum.MEMBER);
                }
                participationMapper.updateById(participation);
            } else {
                // 如果没有参与记录，创建新的参与记录
                participation = new Participation();
                participation.setClubId(clubId);
                participation.setStudentId(studentId);
                participation.setClubPosition(ClubPositionEnum.valueOf(position.toUpperCase()));
                participationMapper.insert(participation);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;  // 确保事务回滚
        }
    }

    //社团审核 社团待审核 已审核 已拒绝
    @Override
    public List<ClubApprovalDTO> getClubsInReview() {
        QueryWrapper<Club> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("club_status", ClubStatusEnum.InReview.getValue());

        return getClubApprovalDTOS(queryWrapper);
    }

    @Override
    public List<ClubApprovalDTO> getApprovedClubs() {
        QueryWrapper<Club> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("club_status", ClubStatusEnum.Open.getValue(), ClubStatusEnum.RestrictJoining.getValue());

        return getClubApprovalDTOS(queryWrapper);
    }

    @Override
    public List<ClubApprovalDTO> getRejectedClubs() {
        QueryWrapper<Club> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("club_status", ClubStatusEnum.Rejected.getValue());

        return getClubApprovalDTOS(queryWrapper);
    }

    private List<ClubApprovalDTO> getClubApprovalDTOS(QueryWrapper<Club> queryWrapper) {
        List<Club> clubs = clubMapper.selectList(queryWrapper);
        return clubs.stream().map(club -> {
            ClubApprovalDTO dto = new ClubApprovalDTO();
            dto.setClubId(club.getClubId());
            dto.setClubName(club.getClubName());
            dto.setCategory(club.getCategory());
            dto.setApplyTime(club.getPublishTime());

            dto.setLeaderName(club.getLeaderName());
            return dto;
        }).collect(Collectors.toList());
    }


    //社团审核 查看详情
    @Override
    public ClubApprovalDetailDTO getClubApprovalDetails(Integer clubId) {
        Club club = clubMapper.selectById(clubId);
        if (club == null) {
            return null;
        }
        ClubApprovalDetailDTO dto = new ClubApprovalDetailDTO();
        dto.setClubId(club.getClubId());
        dto.setClubName(club.getClubName());
        dto.setLeaderId(club.getLeaderId());
        dto.setLeaderName(club.getLeaderName());
        dto.setClubDescription(club.getClubDescription());
        dto.setCategory(club.getCategory());
        dto.setRequirements(club.getRequirements());
        dto.setApplyTime(club.getPublishTime());
        dto.setLogoUrl(club.getLogoUrl());
        dto.setCurrentMembers(club.getCurrentMembers());
        dto.setPublishTime(club.getPublishTime());
        return dto;
    }


    //社团审核 通过 拒绝
    @Transactional
    @Override
    public boolean updateClubStatus(Integer clubId, ClubStatusEnum status) {
        Club club = clubMapper.selectById(clubId);
        if (club != null && club.getClubStatus().equals(ClubStatusEnum.InReview)) {
            club.setClubStatus(status);
            clubMapper.updateById(club);

            // 发送消息给创建人
            Integer creatorId = club.getLeaderId();
            String messageContent = status.equals(ClubStatusEnum.Open) ? "您的社团申请已通过审核。" : "您的社团申请已被拒绝。";
            messageService.sendMessageToStudent(creatorId, clubId, messageContent);

            return true;
        }
        return false;
    }





    @Override
    public void noticeManager(AdminMessage adminMessage){
        adminMessageMapper.insert(adminMessage);
        //加入到数据库中，待管理员自行查看
    }

    @Override
    public Club createNewClub(CreateClubDTO createClubDTO) {

        if (clubMapper.findByName(createClubDTO.getClubName()) != null) {
            throw new RuntimeException("该社团名称已存在");
        }
        // 获取当前用户ID
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer studentId = (Integer) map.get(TokenPayloadEnum.StudentId.getValue());
        String name=(String)map.get(TokenPayloadEnum.Name.getValue());


        Club club=new Club();

        club.setClubName(createClubDTO.getClubName());
        club.setCategory(createClubDTO.getCategory());
        club.setRequirements(createClubDTO.getRequirements());

        club.setLeaderId(studentId);
        club.setLeaderName(name);

        club.setPublishTime(LocalDateTime.now());
        club.setUpdateTime(LocalDateTime.now());

        club.setClubStatus(ClubStatusEnum.InReview);
        //club.setPostPublicScope(PostPublicScopeEnum.MembersVisible);
        club.setPostPublicScope(createClubDTO.getPostPublicScopeEnum());
        club.setPopularity(0);

        club.setClubDescription(createClubDTO.getDescriptionContent());

        try{
            club.setLogoUrl(createClubDTO.uploadPicture().toString());
        }catch (Exception e){
            e.printStackTrace();
        }

        clubMapper.insert(club);

        AdminMessage adminMessage=new AdminMessage();
        adminMessage.setClubId(club.getClubId());
        adminMessage.setSentTime(LocalDateTime.now());
        adminMessage.setMessageContent("用户"+userMapper.selectById(studentId).getName()+"请求创建新社团，社团名称："
                                                                    +club.getClubName()+"，社团类型："+club.getCategory());

        noticeManager(adminMessage);

        //加入一条申请人的participation信息，申请人为这个社团的leader
        Participation participation=new Participation();
        participation.setStudentId(studentId);
        participation.setClubPosition(ClubPositionEnum.LEADER);
        participation.setParticipateTime(LocalDateTime.now());
        participation.setClubId(club.getClubId());
        participationMapper.insert(participation);

        return club;
    }


    @Override
    public boolean clubJoinable(Integer clubId) {

        Club club = clubMapper.selectById(clubId);
        if (club==null) {
            return false;
        }
        ClubStatusEnum clubStatus = club.getClubStatus();
        if (club == null || clubStatus == null) {
            return false;
        }
        if (!(clubStatus.equals(ClubStatusEnum.Open))) {
            return false;
        }

        return true;
    }

    @Override
    public boolean isPostVisibleForUser(Integer clubId,Integer studentId) {

        if (studentId==null) {
            return false;
        }

        Club club=clubMapper.selectById(clubId);

        if (club==null) {
            return false;
        }

        PostPublicScopeEnum postPublicScope=club.getPostPublicScope();


        if (postPublicScope.equals(PostPublicScopeEnum.Hidden)) {

            //若“已隐藏”
            return false;

        } else if (postPublicScope.equals(PostPublicScopeEnum.UserVisible)) {
                //若“用户可见”
                return true;
        } else {

            QueryWrapper<Participation> queryWrapper=new QueryWrapper<>();
            queryWrapper
                .eq("student_id", studentId)
                .eq("club_id", clubId);

            Participation participation=participationService.getOne(queryWrapper);

            if (participation==null) {
                return false;
            }

            if (postPublicScope.equals(PostPublicScopeEnum.AdminVisible)) {

                //若“管理员可见”
                if (participation!=null && participation.getClubPosition().equals(ClubPositionEnum.MEMBER)) {
                    return false;
                } else {
                    return true;
                }
            }
        }

        return true;
    }

    @Override
    public boolean hasCommunityContentPublishPower(Integer clubId, Integer studentId) {

        if (studentId==null) {
            return false;
        }

        Club club=clubMapper.selectById(clubId);

        if (club==null) {
            return false;
        }

        PostPublicScopeEnum postPublicScope=club.getPostPublicScope();

        if (postPublicScope.equals(PostPublicScopeEnum.Hidden)) {

            //若“已隐藏”
            return false;

        } else {

            ClubPositionEnum clubPositionEnum=participationService.getclubPositionOfUser(clubId);

            if (clubPositionEnum.equals(ClubPositionEnum.NONE)) {

                //如果非成员
                return false;
            }

            if (postPublicScope.equals(PostPublicScopeEnum.AdminVisible)) {

                //若动态“管理员可见”

                if (clubPositionEnum.equals(ClubPositionEnum.MEMBER)) {

                    //如果用户是“普通成员”
                    return false;

                } else {

                    //如果用户是该社团的“二把手”或“一把手”
                    return true;
                }
            }
        }

        return true;
    }

    @Override
    public Club updateClubInfo(Integer clubId, ClubUpdateRequestDTO updateRequest) {
        Club existingClub = clubMapper.selectById(clubId);
        if (existingClub == null) {
            return null;
        }
        if(!isSuchClubPosition(LEADER,clubId)){
            return null;
        }

        if (updateRequest.getClubDescription() != null) {
            existingClub.setClubDescription(updateRequest.getClubDescription());
        }

        if (updateRequest.getRequirements() != null) {
            existingClub.setRequirements(updateRequest.getRequirements());
        }
        existingClub.setPostPublicScope(updateRequest.getPostPublicScope());
        existingClub.setCategory(updateRequest.getCategory());
        existingClub.setClubStatus(updateRequest.getClubStatus());
        if (clubMapper.updateById(existingClub) == 1) {
            return existingClub;
        }
        return null;
    }

    @Override
    public void updateClubPopularity() {
        List<Club> clubs = clubMapper.selectList(null);
        for (Club club : clubs) {
            int clubId = club.getClubId();

            int recentFootPrints = getRecentFootPrints(clubId);
            int recentActivities = getRecentActivities(clubId);
            int recentPosts = getRecentPosts(clubId);
            int recentComments = getRecentComments(clubId);
            int recentApplications = getRecentApplications(clubId);

            double popularity = 5*(clubPopularityConfig.getWeights().getFootprints() * recentFootPrints
                    + clubPopularityConfig.getWeights().getActivities() * recentActivities
                    + clubPopularityConfig.getWeights().getPosts() * recentPosts
                    + clubPopularityConfig.getWeights().getComments() * recentComments
                    + clubPopularityConfig.getWeights().getApplications() * recentApplications);

            club.setPopularity((int) popularity);
            clubMapper.updateById(club);
        }
    }

    /**
     * 一把手删除社团
     * @param clubId
     * @return
     */
    @Override
    public boolean deleteClub(int clubId) {
        Map<String,Object> map=ThreadLocalUtil.get();
        Integer studentId=(Integer)map.get(TokenPayloadEnum.StudentId.getValue());
        User user=userMapper.selectById(studentId);
        if(!isSuchClubPosition(ClubPositionEnum.LEADER,clubId)&&!user.getUserType().equals(UserTypeEnum.administrator)) {
            return false;
        }
        String content=clubMapper.selectById(clubId).getClubName()+"已解散";
        int result=clubMapper.deleteById(clubId);
        if(result==1){

            notifyAllMembers(clubId,content);
            return true;
        }
        return false;
    }

    private int getRecentFootPrints(int clubId) {
        QueryWrapper<Footprint> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("club_id", clubId).ge("browse_time", LocalDateTime.now().minusDays(recentPeriodConfig.getDays()));
        return Math.toIntExact(footPrintMapper.selectCount(queryWrapper));
    }

    private int getRecentActivities(int clubId) {
        return Math.toIntExact(activityMapper.selectCount(new QueryWrapper<Activity>()
                .eq("club_id", clubId)
                .ge("publish_time", LocalDateTime.now().minusDays(recentPeriodConfig.getDays()))));
    }

    private int getRecentPosts(int clubId) {
        return Math.toIntExact(postMapper.selectCount(new QueryWrapper<Post>()
                .eq("club_id", clubId)
                .ge("publish_time", LocalDateTime.now().minusDays(recentPeriodConfig.getDays()))));
    }

    private int getRecentComments(int clubId) {
        return Math.toIntExact(commentMapper.selectCount(new QueryWrapper<Comment>()
                .inSql("post_id", "SELECT post_id FROM post WHERE club_id = " + clubId)
                .ge("comment_time", LocalDateTime.now().minusDays(recentPeriodConfig.getDays()))));
    }

    private int getRecentApplications(int clubId) {
        return Math.toIntExact(applicationMapper.selectCount(new QueryWrapper<Application>()
                .eq("club_id", clubId)
                .ge("apply_time", LocalDateTime.now().minusDays(recentPeriodConfig.getDays()))));
    }

    @Override
    public Club getClubInfo(Integer clubId) {
        footprintService.addFootprint(clubId);
        if (isClubsVisibleForUser(clubId)) {
            return clubMapper.selectById(clubId);
        }
        return null;
    }

    @Override
    public String changeLogo(MultipartFile logo,int clubId) {
        String originalFileName=logo.getOriginalFilename();
        if (originalFileName==null) {
            return null;
        }
        String savedfileName = imageDirectory+ UUID.randomUUID().toString()
                + originalFileName.substring(originalFileName.lastIndexOf("."));

        try{
            String result=ObsUtil.uploadFile(savedfileName, logo.getInputStream());
            Club club=clubMapper.selectById(clubId);
            club.setLogoUrl(result);
            clubMapper.updateById(club);
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Club selectById(Integer clubId) {
        return clubMapper.selectById(clubId);
    }

    /*
    * 更换一把手
    * */
    @Override
    public User changeLeader(int newLeaderId,int clubId) {
        //验证当前用户是不是一把手
        if(!isSuchClubPosition(LEADER,clubId)){
            return null;
        }
        //验证studentId这个用户在不在社团里
        QueryWrapper<Participation> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("student_id",newLeaderId)
                .eq("club_id",clubId);
        if(participationService.count(queryWrapper)==0){
            return null;
        }
        Club club=clubMapper.selectById(clubId);
        club.setLeaderId(newLeaderId);
        club.setLeaderName(userMapper.selectById(newLeaderId).getName());
        clubMapper.updateById(club);

        //更新Participation表
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer studentId = (Integer) map.get(TokenPayloadEnum.StudentId.getValue());

        //设置新一把手的信息
        QueryWrapper<Participation> newLeaderQueryWrapper = new QueryWrapper<>();
        newLeaderQueryWrapper.eq("student_id", newLeaderId)
                .eq("club_id", clubId);
        Participation newLeaderParticipation = participationService.getOne(newLeaderQueryWrapper);
        if (newLeaderParticipation != null) {
            newLeaderParticipation.setClubPosition(LEADER);
            participationService.updateById(newLeaderParticipation);
        }

        // 设置旧一把手的信息
        QueryWrapper<Participation> currentLeaderQueryWrapper = new QueryWrapper<>();
        currentLeaderQueryWrapper.eq("student_id", studentId)
                .eq("club_id", clubId);
        Participation currentLeaderParticipation = participationService.getOne(currentLeaderQueryWrapper);
        if (currentLeaderParticipation != null) {
            currentLeaderParticipation.setClubPosition(SECOND_LEADER);
            participationService.updateById(currentLeaderParticipation);
        }
        String content=club.getClubName()+"的一把手由"+userMapper.selectById(studentId).getName()+"更换成"+userMapper.selectById(newLeaderId).getName();
        notifyAllMembers(clubId,content);
        return userMapper.selectById(newLeaderId);
    }


    /*
     * 一把手踢人
     * */
    @Override
    public boolean kick(int userId,int clubId) {
        //userId是被踢的人的学号
        if(!isSuchClubPosition(ClubPositionEnum.LEADER,clubId)){
            return false;
        }
        QueryWrapper<Participation> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("student_id",userId)
                .eq("club_id",clubId);
        Participation participation=participationService.getOne(queryWrapper);
        if(participation==null){
            return false;
        }
        if(participation.getClubPosition().equals(MEMBER)){
            participationService.deleteById(participation);
            messageService.sendMessageToStudent(userId,clubId,"你已被"+clubMapper.selectById(clubId).getClubName()+"踢出");
            //踢出去之后把之前的申请信息删掉
            QueryWrapper<Application> applicationQueryWrapper=new QueryWrapper<>();
            applicationQueryWrapper.eq("student_id",userId)
                    .eq("club_id",clubId);
            Application application=applicationMapper.selectOne(applicationQueryWrapper);
            System.out.println(application);
            applicationMapper.deleteById(application);
            return true;
        }
        return false;
    }


    /*
    * 浏览社团
    * */
    @Override
    public Page<Club> browseClubs(int pageNum, String category) {
        int pageSize=8;
        QueryWrapper<Club> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("club_status",ClubStatusEnum.Open);
        queryWrapper.orderByDesc("popularity");
        //返回对应社团
        if(clubCategory.getClubCategoryList().contains(category)){
            queryWrapper
                    .eq("category", category)
                    .in("club_status", ClubStatusEnum.Open,ClubStatusEnum.RestrictJoining);
        }
        //不设置查询类别，或类别不符合要求，返回全部社团

        Page<Club> page = new Page<>(pageNum, pageSize);
        return clubMapper.selectPage(page, queryWrapper);
    }


    /*
    * 退出社团
    * */
    @Override
    public boolean quitClub(int clubId) throws JsonProcessingException {
        Map<String,Object> map=ThreadLocalUtil.get();
        Integer studentId=(Integer)map.get(TokenPayloadEnum.StudentId.getValue());
        QueryWrapper<Participation> participationQueryWrapper=new QueryWrapper<>();
        participationQueryWrapper.eq("club_id",clubId)
            .eq("student_id",studentId);

        // 查询用户在不在社团里
        Participation participation = participationService.getOne(participationQueryWrapper);
        if (participation == null) {
            return false;
        }

        if (participation.getClubPosition().equals(ClubPositionEnum.LEADER)) {

            throw new RuntimeException("社团一把手不能直接退出社团");
            //社团一把手不能直接退出社团
            // return false;
        }

        boolean removed = participationService.removeById(participation);
        QueryWrapper<Application> applicationQueryWrapper=new QueryWrapper<>();
        applicationQueryWrapper.eq("student_id",studentId)
                        .eq("club_id",clubId);
        applicationMapper.delete(applicationQueryWrapper);
        if(removed){

            //如果这个人是二把手
            if(participation.getClubPosition().equals(SECOND_LEADER)){
                //从二把手名单中移除这个人
                Club club=clubMapper.selectById(clubId);
                List<Integer> secondManagers = objectMapper.readValue(club.getSecondManager(), new TypeReference<List<Integer>>() {});
                secondManagers.remove(studentId);
                club.setSecondManager(objectMapper.writeValueAsString(secondManagers));
                return true;
            }
            return true;
        }
        return false;
    }

    @Override
    public boolean isClubsVisibleForUser(Integer clubId) {

        if (clubId==null) {
            return false;
        }

        Club club=clubMapper.selectById(clubId);

        if (club==null) {
            return false;
        }

        ClubStatusEnum clubStatusEnum=club.getClubStatus();

        if (clubStatusEnum==null) {
            return false;
        }

        if (clubStatusEnum.equals(ClubStatusEnum.Open)||clubStatusEnum.equals(ClubStatusEnum.RestrictJoining)) {
            return true;
        }

        return false;
    }

    @Override
    public Participation memberToSecondLeader(int clubId, int memberId) throws JsonProcessingException {
        if(!isSuchClubPosition(LEADER, clubId)){
            return null;
        }
        QueryWrapper<Participation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("club_id", clubId)
                .eq("student_id", memberId)
                .eq("club_position", "普通成员");

        Participation participation = participationService.getOne(queryWrapper);
        if(participation == null){
            return null;
        }
        participation.setClubPosition(SECOND_LEADER);

        // 获取 club 实例
        Club club = clubMapper.selectById(clubId);
        List<Integer> secondManagers;

        // 如果 secondManager 为空，则初始化一个空列表
        if(club.getSecondManager() == null || club.getSecondManager().isEmpty()) {
            secondManagers = new ArrayList<>();
        } else {
            secondManagers = objectMapper.readValue(club.getSecondManager(), new TypeReference<List<Integer>>() {});
        }
        //最多3个二把手
        if(secondManagers.size()==3){
            return null;
        }
        // 将 memberId 加入到二把手名单中
        secondManagers.add(memberId);
        club.setSecondManager(objectMapper.writeValueAsString(secondManagers));
        clubMapper.updateById(club); // 确保更新 club 信息

        participationMapper.updateById(participation);

        if (participation!=null) {
            messageService.sendMessageToStudent(participation.getStudentId(), participation.getClubId(),"您已被设置为社团二把手");
        }

        return participation;
    }


    @Override
    public Participation secondLeaderToMember(int clubId, int memberId) throws JsonProcessingException {
        if(!isSuchClubPosition(LEADER, clubId)){
            return null;
        }
        QueryWrapper<Participation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("club_id", clubId)
                .eq("student_id", memberId)
                .eq("club_position", "二把手");
        Participation participation = participationService.getOne(queryWrapper);
        if(participation == null){
            return null;
        }
        participation.setClubPosition(MEMBER);

        // 获取 club 实例
        Club club = clubMapper.selectById(clubId);
        List<Integer> secondManagers;

        // 如果 secondManager 为空，则初始化一个空列表
        if(club.getSecondManager() == null || club.getSecondManager().isEmpty()) {
            secondManagers = new ArrayList<>();
        } else {
            secondManagers = objectMapper.readValue(club.getSecondManager(), new TypeReference<List<Integer>>() {});
        }

        // 移出二把手名单

        secondManagers.remove((Integer) memberId);
        club.setSecondManager(objectMapper.writeValueAsString(secondManagers));
        clubMapper.updateById(club); // 确保更新 club 信息

        participationMapper.updateById(participation);

        if (participation!=null) {
            messageService.sendMessageToStudent(participation.getStudentId(), participation.getClubId(), "您已被设置为社团普通成员");
        }

        return participation;
    }


    /**
     * （更换一把手，或解散社团时）通知所有社团成员
     */
    public void notifyAllMembers(int clubId,String content){
        QueryWrapper<Participation> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("club_id",clubId)
                .select("student_id");

        List<Participation> participation = participationService.selectList(queryWrapper);
        // 提取 student_id 字段，存到一个List里
        List<Integer> studentIds = participation.stream()
                .map(Participation::getStudentId)
                .collect(Collectors.toList());
        for(int studentId:studentIds){
            messageService.sendMessageToStudent(studentId,clubId,content);
        }
    }

    @Override
    public Page<Application> pendingApplications(int pageNum, int pageSize) {
        Map<String,Object> map=ThreadLocalUtil.get();
        Integer studentId=(Integer)map.get(TokenPayloadEnum.StudentId.getValue());

        QueryWrapper<Participation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", studentId)
                .and(wrapper -> wrapper
                        .eq("club_position", "一把手")
                        .or()
                        .eq("club_position", "二把手")
                )
                .select("club_id");

        List<Participation> participation = participationService.selectList(queryWrapper);
        // 提取 club_id 字段，存到一个List里
        List<Integer> clubIds = participation.stream()
                .map(Participation::getClubId)
                .collect(Collectors.toList());
        QueryWrapper<Application> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.in("club_id",clubIds)
                .eq("approval_status","审核中");

        Page<Application> page = new Page<>(pageNum, pageSize);

        // 分页查询
        return applicationMapper.selectPage(page, queryWrapper1);
    }

}
